package com.example.springfeature.classloader;


import com.example.springfeature.createobject.User;

/**
 * Created with IDEA
 *
 * @author: 董文辉
 * Date: 2019/3/1
 * Time: 12:02
 */
public class ClassLoaderTest {
    public static void main(String[] args) throws Exception {
        //获取类加载器的树形结构
        /*User user = new User();
        ClassLoader classLoader = user.getClass().getClassLoader();
        while(classLoader != null){
            System.out.println(classLoader);
            classLoader = classLoader.getParent();
        }*/
        MyClassLoader mc = new MyClassLoader();
//        Class<?> classOne = Class.forName("com.example.springfeature.createobject.User", true, mc);
        Class<?> classOne = Class.forName("com.example.springfeature.createobject.User", true, User.class.getClassLoader());
        Object o = classOne.newInstance();
        System.out.println(o);
        System.out.println("classOne使用的类加载器是： "+o.getClass().getClassLoader());

//        MyClassLoader mc1 = new MyClassLoader();
//        Class<?> classTwo = Class.forName("com.example.springfeature.createobject.User", true, mc1);
        Class<?> classTwo = Class.forName("com.example.springfeature.createobject.User", true, User.class.getClassLoader());
        Object o1 = classTwo.newInstance();
        System.out.println(o1);
        System.out.println("classTwo使用的类加载器是： "+o1.getClass().getClassLoader());
        //将classOne 的实例强转为classTwo类型
        o1 = classTwo.cast(o);
        System.out.println(o1);

    }
}
